<?
 Prado::using('System.Web.UI.ActiveControls.*'); 
 Prado::using('System.Web.TAssetManager.*'); 
 Prado::using('System.Data.ActiveRecord.*');
 Prado::using('Application.pages.utils.CommonUtils');
 
class ProfileUser extends TPage
{
	public $found = "true";
	//public $serverPathDownload = "userimages/";
	//public $serverPathDownload = "assets/images/";
	// navigated id
	public $id = -1;
	public $currentRecord = null;
	public $ownerRecord = null;
	
	public function onInit($param)
    {	
//			parent::onInit($param);
			if(!$this->IsPostBack)  // if the page is requested the first time
			{
				//echo "IsPostBack";
				
			}

			$this->id = $this->Request['id'];
			
			// writing current id for js to access :: NOT SECURED
			echo "<input type=\"hidden\" id=\"uid\"  value=\"". $this->id."\" />";
			
			
			// owner made request Repeater
			$this->Repeater->VirtualItemCount = FriendReqRecord::finder()->count('user_id = ?',$this->id);
			// someone requested Repeater
			$this->Repeater_requested->VirtualItemCount = FriendReqRecord::finder()->count('friend_id = ?',$this->id);
			
			// activity Repeater		
			$this->Repeater_activity->VirtualItemCount = $this->getActivityCount();
			// friend Repeater
			$f_1 = FriendRecord::finder()->count('user_id = ?',$this->id);
			$f_2 = FriendRecord::finder()->count('friend_id = ?',$this->id);
			$this->numFriend->Text = "(". ($f_1 + $f_2) . ")";
			$this->Repeater_friend->VirtualItemCount = $f_1 + $f_2;
		
			// profile comments
			$this->Repeater_ProfileComments->VirtualItemCount = ProfileCommentsRecord::finder()->count('owner_user_id = ?',$this->id);
			
           // $this->Repeater->VirtualItemCount=FriendReqRecord::finder()->count();
            // populates post data into the repeater
            $this->populateData();
			$this->populateData_requested();
			$this->populateData_friend();
			$this->populateData_activity();
        	$this->populateData_profile_comments();	
		
			//// init showing logic
			$this->initCurrentProfile();
		    $this->verifyOwner();
			
			
			//************ for friends check
			// if they're friends.. or private = 0
			if($this->alreadyFriends()) 
			{
//				$this->contentActivity->Visible = true;
//				$this->contentProfile->Visible = true; // hide this cnt
				$this->restrictedUserCnt->Visible = false; 
//				$this->navigatedUserCnt->Visible = true;
				
			}
			else // they're not friends yet , private = 1
			{
				$this->navigatedUserCnt->Visible = false;
				$this->contentActivity->Visible = false; // hide this cnt
				$this->contentProfile->Visible = false; // hide this cnt
				
//				$this->restrictedUserCnt->Visible = true; // show this cnt
				$this->setRestrictedUserCntText();

			}
			
		//echo $this->ownerAvatar->ImageUrl . "sss";
    }
	
	public function initFriendsUpdatedCnt()
	{
		// activity Repeater		
		$this->Repeater_friends_activity->VirtualItemCount = $this->getFriendsActivityCount();
		$this->populateData_friends_activity();	

	}
	
	protected function populateData_friends_activity()
    {
        $offset=$this->Repeater_friends_activity->CurrentPageIndex*$this->Repeater_friends_activity->PageSize;
        $limit=$this->Repeater_friends_activity->PageSize;
        if($offset + $limit > $this->Repeater_friends_activity->VirtualItemCount)
            $limit=$this->Repeater_friends_activity->VirtualItemCount-$offset;
        $this->Repeater_friends_activity->DataSource=$this->getRequests_friends_activity($offset,$limit);
		
        $this->Repeater_friends_activity->dataBind();

    }
	
	protected function getRequests_friends_activity($offset, $limit)
    {
        $criteria=new TActiveRecordCriteria;
		$list = $this->getFriendIDs();
		
		// can be used like this >> $criteria->Condition = 'owner_id in '.$this->getOwnerFriendIDs();
		$criteria->Condition = 'actor_id in '.$list . ' or dotouser_id in '. $list;
		//$criteria->Parameters[':id'] = $this->id;
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
        $criteria->OrdersBy['id'] = 'desc';
		//echo $criteria;

        // query for the posts with the above criteria and with author information
        return ActivityRecord::finder()->findAll($criteria);
    }
	
	public function pageChanged_friends_activity($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_friends_activity->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData_friends_activity();
    }
	
	public function getFriendsActivityCount()
	{
		$list = $this->getFriendIDs();
			// leave 2nd arguments empty
		
		$num_actor = ActivityRecord::finder()->count("actor_id in " . $list. " or dotouser_id in ". $list, "");
		//echo "List ". $list;
		return $num_actor;
	}
	
	public function verifyOwner()
	{
		if($this->isNavigatedUserSameAsOwner())
		{ // showing owner profile...
		
			$this->txtStatusHeader->Text = "What are you doing now >>>> ";
			$this->txtRecentActivity->Text = "My recent updated activities (".$this->Repeater_activity->VirtualItemCount .")" ;
			$this->scriptElement->Visible = true;
			
			
			// Friends update CNT
			$this->initFriendsUpdatedCnt();
		}			
		else // showing someone else profile
		{
			$this->txtStatusHeader->Text = "What is <strong>" . $this->getCurrentRecord()->username . "</strong> doing now >>>> ";
			$this->txtRecentActivity->Text = "<strong>" . $this->getCurrentRecord()->username . "</strong> updated activities (".$this->Repeater_activity->VirtualItemCount .")" ;
			$this->scriptElement->Visible = false;
			// removing edit profile/send req/friends update
			$this->removeOwnerCmp();
		}
	}
	
	public function initCurrentProfile()
	{
		$this->setTitle($this->getCurrentRecord()->username ."'s Profile");
		$this->txtDisplayName->Text = $this->getCurrentRecord()->username;		
		$this->txtUserStatus->Text = $this->getCurrentRecord()->userStatus;
		
		
			
	}
	
	public function setRestrictedUserCntText()
	{
		$target_finder = UserRecord::finder()->findByEmail($this->getCurrentRecord()->email);		
		$target_id = $target_finder->user_id;
		
		$self_id = $this->getOwnerRecord()->user_id;
	
		$count = FriendReqRecord::finder()->count('user_id = ? AND friend_id = ?',$target_id ,$self_id);
		$countR = FriendReqRecord::finder()->count('user_id = ? AND friend_id = ?',$self_id ,$target_id);
		//echo "<br>count " . ($count + $countR);
		$str = "This profile are strictly private.<br/>";
		if($count + $countR  > 0)
		{
			$this->btnFriendReq->Visible = false;
			$str = $str . "You or him/her already made a request,... please wait until other party accepts";
			
		}
		else 
		{
			$this->btnFriendReq->Visible = true;
			$str = $str ."Please add friends to him/her first... ";
		}	
		$this->restrictTxt->Text = $str;	
	}
	
	public function alreadyFriends()
	{
		// if we're watching our own profile...
		if($this->isNavigatedUserSameAsOwner())
			return true;
			
		// else watching someone else's profile
		$owner = $this->getOwnerRecord();
		$navigated = $this->getCurrentRecord();
		if($navigated->isPrivate == 0) // not private
			return true;	
		else // private, need to verify that $owner , $navigated are friends
		{
			$str_friends = $this->getFriendIDs();
			if(strstr($str_friends,$this->user->ID)) // if found >> they're friends
			{
//				echo "they're friends";
				return true;	
			}
			else
			{
//				echo "they're NOT friends";
				return false;
			}
						
		}
		
	}

	
	public function getActivityCount()
	{
			
			// leave 2nd arguments empty
			
			$num_actor = ActivityRecord::finder()->count("actor_id = " . $this->id . " or dotouser_id = ". $this->id, "");
			
			return $num_actor;
	}
	
	// this method will return the owner's friend ids in type of "(1,2,3,...)"...
	// use in (1,2,..)
	public function getFriendIDs()
	{
		$ret = array();

		/////  Find all possible friends ids		
		/// search user_id , use friend_id
		$rec = FriendRecord::finder()->findAll('user_id = ?',$this->id);
			
		for($i = 0;$i < sizeof($rec);$i++)
		{
			array_push($ret,$rec[$i]->friend_id);
	

		}
		/// search friend_id , use user_id
		$rec2 = FriendRecord::finder()->findAll('friend_id = ?',$this->id);
		for($i = 0;$i < sizeof($rec2);$i++)
		{	
			array_push($ret,$rec2[$i]->user_id);
		}		
		
		//// convert array int to be "(1,2,3,....)"
		$str = "";
		if(sizeof($ret) > 0)
			for($i = 0;$i < sizeof($ret);$i++)
			{
				$str = $str . $ret[$i];
				if($i != sizeof($ret) - 1)
					$str = $str . ",";
			}
		else
			$str = "0"; // there're no user id '0'
			
		$str = "(" .$str . ")";
		//echo $str;
		//exit();
		//die();
		return $str;
	}
	
	public function isNavigatedUserSameAsOwner()
	{
		return $this->id == $this->user->ID;
	}
	
	public function btnEditProfile($sender, $param)
    {	
    	$this->updateEditProfileDB();
    	$rec = $this->updateEditProfileForActivity();
		$this->updateActivityProfileEdit($rec);
		
		// refresh page
		$this->onInit($param);
	}
	
	public function updateEditProfileForActivity()
	{
		$rec = new UpdateProfileRecord();
		$rec->user_id = $this->user->ID;
		$rec->update_datetime = date("Y/m/d H:i:s");
		$rec->save();
		return $rec;
	}
	
	public function updateActivityProfileEdit($rec)
	{
		$profileActivity = new ActivityRecord();
		$profileActivity->activity_id = 2;
		$profileActivity->actor_id = $this->user->ID;
		$profileActivity->rec_id = $rec->id;		
		$profileActivity->dotouser_id = -1;
		$profileActivity->save();
	}
	
	public function updateEditProfileDB()
	{
		// before getting here... every thing must be filled + correct
		$owner = $this->getOwnerRecord();
		$owner->first_name = $this->firstName->Text;
		$owner->last_name = $this->lastName->Text;
		$owner->password = $this->pw->Text;
		$owner->birthDate =  $this->DDLYear->SelectedItem->Text."-".
						$this->DDLMonth->SelectedItem->Value."-".
						$this->DDLDay->SelectedItem->Text;
		$owner->isPrivate = $this->isPrivateChk->Checked;
		
		$sex = -1;
		if($this->radMale->Checked)
			$sex = 1;
		else if($this->radFemale->Checked)
			$sex = 0;		
	   	$owner->sex = $sex;
	   	
		$owner->save();
	}
	
	public function removeOwnerCmp()
	{
		// disable edit profile link
		$this->linkEditProfile->Visible = false;
			
		//disable friends update
		$this->ownerInfoCnt->Visible = false;
	}
	// for fileUploaded
	public function fileUploaded($sender,$param)
    {
		echo "<br/>".$sender->HasFile."<br/>".$sender->FileName;
        if($sender->HasFile)
        {
			$size = $sender->FileSize / 1024;
			if($size > 500)
				echo "Error : file size exceeded the limits";
			else
			{
				
				//**** at server used >>>	$path = $this->Application->AssetManager->getBasePath() ."/images/". $this->id ."/";
				$path = $this->Application->AssetManager->getBasePath() ."\\images\\". $this->id ."\\";
				// directory is not exists
				if(is_dir($path) == null)
				{
					
					mkdir($path,0777,true);
				}
					
				
				
			 	$sender->saveAs($path . $sender->FileName);
				$this->deleteOldPic();
				$this->updateAvatarDB($sender->FileName);
				$this->Response->reload();
			}
        }
		else
			echo "Error : file doesn't exists";
    }

	public function deleteOldPic()
	{
		$old_path = $this->getCurrentRecord()->avatarPath;
		if($old_path != null)
		{	
			//**** at server used >>>	$path = $this->Application->AssetManager->getBasePath() ."/images/". $this->id ."/";
			$old_path = $this->Application->AssetManager->getBasePath() ."\\images\\". $this->id ."\\". $old_path;
			//die($old_path);
			$flgDelete = unlink($old_path);
			if($flgDelete)
				echo "File deleted";
			else
				echo "File cannot be deleted";
		}
		
	}
	
	public function updateAvatarDB($filename)
	{
		$user = $this->getOwnerRecord();
		$user->avatarPath = $filename; //change property
		$user->save();
		
	}

	public function resetAvatar()
	{
		$this->deleteOldPic();
		$this->updateAvatarDB(null);
		$this->Response->reload();
	}

	public function btnCommentClicked($sender, $param)
    {
			// avoid empty text case	
		$body = trim($this->taComment->getText());
		if($body != "")
		{
			$rec = $this->updateProfileDB($body);
			$this->updateActivityProfile($rec);
			
		}
		// set comment text to be empty
		$this->taComment->setText("");
		$this->onInit($param); // call this onInit to refresh the page
    }

	public function updateActivityProfile($rec)
	{
		$profileActivity = new ActivityRecord();
		// use navigated user id
		//$profileActivity->user_id = $this->user->ID;
		// use owner user id
		//$profileActivity->friend_id = $this->id;
		
		$profileActivity->activity_id = 1;
		$profileActivity->rec_id = $rec->id;
		$profileActivity->actor_id = $this->user->ID;
		$profileActivity->dotouser_id = $this->id;
		$profileActivity->save();
	}
	
	public function updateProfileDB($body)
	{
			$comment = new ProfileCommentsRecord();
			// use navigated user id
			$comment->owner_user_id = $this->id;
			// use owner user id
			$comment->commentator_user_id = $this->user->ID;
			$comment->body = $body;
			$comment->comment_datetime = date("Y/m/d H:i:s");
			$comment->save();
			return $comment;
	}
	
	
	
	public function buttonRequestedClicked($sender, $param)
    {
		
        $f_email = $this->getCurrentRecord()->email;
		echo "buttonRequestedClicked ".$f_email;
		$finder = UserRecord::finder()->findByEmail($f_email);
		$this->insertRecord($finder);	
		$url = $this->Service->constructUrl('users.ProfileUser',array('id' => $this->user->ID));
        $this->Response->redirect($url);
		//$this->onInit($param); // call this onInit to refresh the page
		
    }
	
	public function insertRecord($finder)
	{
		$f_id = $finder->user_id;
		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
		
		$u_id = $this->User->ID;
		$newRec = new FriendReqRecord();
		$newRec->user_id = $u_id;
		$newRec->friend_id = $f_id;
		$newRec->datetime_request = date("Y/m/d H:i:s");
		$newRec->save();
	}
	
	
	protected function populateData_profile_comments()
    {
        $offset=$this->Repeater_ProfileComments->CurrentPageIndex*$this->Repeater_ProfileComments->PageSize;
        $limit=$this->Repeater_ProfileComments->PageSize;
        if($offset + $limit > $this->Repeater_ProfileComments->VirtualItemCount)
            $limit=$this->Repeater_ProfileComments->VirtualItemCount-$offset;
        $this->Repeater_ProfileComments->DataSource=$this->getRequests_profile_comments($offset,$limit);
        $this->Repeater_ProfileComments->dataBind();
	//	echo $this->Repeater->VirtualItemCount;
    }
	
	protected function populateData_activity()
    {
        $offset=$this->Repeater_activity->CurrentPageIndex*$this->Repeater_activity->PageSize;
        $limit=$this->Repeater_activity->PageSize;
        if($offset + $limit > $this->Repeater_activity->VirtualItemCount)
            $limit=$this->Repeater_activity->VirtualItemCount-$offset;
        $this->Repeater_activity->DataSource=$this->getRequests_activity($offset,$limit);
		
        $this->Repeater_activity->dataBind();
	//	echo $this->Repeater->VirtualItemCount;
    }
	
    protected function populateData_friend()
    {
        $offset=$this->Repeater_friend->CurrentPageIndex*$this->Repeater_friend->PageSize;
        $limit=$this->Repeater_friend->PageSize;
        if($offset+$limit > $this->Repeater_friend->VirtualItemCount)
            $limit=$this->Repeater_friend->VirtualItemCount-$offset;
        $this->Repeater_friend->DataSource=$this->getRequests_friend($offset,$limit);
        $this->Repeater_friend->dataBind();
	//	echo $this->Repeater->VirtualItemCount;
    }
 
 	protected function populateData_requested()
    {
        $offset=$this->Repeater_requested->CurrentPageIndex*$this->Repeater_requested->PageSize;
        $limit=$this->Repeater_requested->PageSize;
        if($offset+$limit > $this->Repeater_requested->VirtualItemCount)
            $limit=$this->Repeater_requested->VirtualItemCount-$offset;
        $this->Repeater_requested->DataSource=$this->getRequests_requested($offset,$limit);
        $this->Repeater_requested->dataBind();
	//	echo $this->Repeater->VirtualItemCount;
    }
	
	protected function getRequests_friend($offset, $limit)
    {
        // Construts a query criteria
        $criteria=new TActiveRecordCriteria;
		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
		
		$criteria->Condition = 'friend_id = :id OR user_id = :id';
		$criteria->Parameters[':id'] = $this->id;
        
		
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
	//	echo $criteria;
		//return;
        // query for the posts with the above criteria and with author information
        return FriendRecord::finder()->findAll($criteria);
    }
	
	protected function getRequests_profile_comments($offset, $limit)
    {
        // Construts a query criteria
        $criteria=new TActiveRecordCriteria;
		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
		
		$criteria->Condition = 'owner_user_id = :id';
		$criteria->Parameters[':id'] = $this->id;
        $criteria->OrdersBy['comment_datetime']='desc';
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
	//	echo $criteria;
		//return;
        // query for the posts with the above criteria and with author information
        return ProfileCommentsRecord::finder()->findAll($criteria);
    }
	
	protected function getRequests_activity($offset, $limit)
    {
        $criteria=new TActiveRecordCriteria;
		
		// can be used like this >> $criteria->Condition = 'owner_id in '.$this->getOwnerFriendIDs();
		$criteria->Condition = 'actor_id = :id or dotouser_id = :id';
		$criteria->Parameters[':id'] = $this->id;
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
        $criteria->OrdersBy['id'] = 'desc';
        
		//echo $criteria;
	//	die();
		
		//return;
        // query for the posts with the above criteria and with author information
        return ActivityRecord::finder()->findAll($criteria);
    }
	
	protected function getRequests_requested($offset, $limit)
    {
        // Construts a query criteria
        $criteria=new TActiveRecordCriteria;
		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
		
		$criteria->Condition = 'friend_id = :friend_id ';
		$criteria->Parameters[':friend_id'] = $this->id;
        $criteria->OrdersBy['datetime_request']='desc';
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
	//	echo $criteria;
		//return;
        // query for the posts with the above criteria and with author information
        return FriendReqRecord::finder()->findAll($criteria);
    }
 
 	public function pageChanged_profile_comments($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_ProfileComments->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData_profile_comments();
    }
 
 	public function pageChanged_activity($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_activity->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData_activity();
    }
 
 	public function pageChanged_friend($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_friend->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData_friend();
    }
 
    public function pageChanged_requested($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater_requested->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData_requested();
    }
	
    public function pageChanged($sender,$param)
    {
        // change the current page index to the new one
        $this->Repeater->CurrentPageIndex=$param->NewPageIndex;
        // re-populate data into the repeater
        $this->populateData();
    }
 
  
    protected function populateData()
    {
        $offset=$this->Repeater->CurrentPageIndex*$this->Repeater->PageSize;
        $limit=$this->Repeater->PageSize;
        if($offset+$limit > $this->Repeater->VirtualItemCount)
            $limit=$this->Repeater->VirtualItemCount-$offset;
        $this->Repeater->DataSource=$this->getRequests($offset,$limit);
        $this->Repeater->dataBind();
	//	echo $this->Repeater->VirtualItemCount;
    }
 
   
	
    protected function getRequests($offset, $limit)
    {
        // Construts a query criteria
        $criteria=new TActiveRecordCriteria;
		//$owner = UserRecord::finder()->findByEmail($this->user->Email);
		
		$criteria->Condition = 'user_id = :user_id ';
		$criteria->Parameters[':user_id'] = $this->id;
        $criteria->OrdersBy['datetime_request']='desc';
        $criteria->Limit=$limit;
        $criteria->Offset=$offset;
	//	echo $criteria;
		//return;
        // query for the posts with the above criteria and with author information
        return FriendReqRecord::finder()->findAll($criteria);
    }
	
	public function getOwnerRecord()
	{
		// use lazy init
	//	$userRecord = UserRecord::finder()->findByEmail($this->user->Email); $this->id
		if($this->ownerRecord == null)
			$this->ownerRecord = UserRecord::finder()->findByUser_Id($this->user->ID);
		return $this->ownerRecord;
	}
	
	public function getCurrentRecord()
	{
		// use lazy init
	//	$userRecord = UserRecord::finder()->findByEmail($this->user->Email); $this->id
		if($this->currentRecord == null)
			$this->currentRecord = UserRecord::finder()->findByUser_Id($this->id);
		return $this->currentRecord;
	}
	
	public function getSexString($sex)
	{
	
		if($sex == 0)
			return "Female";
		else
			return "Male";
	}

	public function getAvatar($user)
	{
		$img_path = $this->Application->Parameters['ImageFolderName'];
		return CommonUtils::getAvatar($img_path,$user);		
	}
	
	

}


?>